package br.hm.telephoneoperator.impl;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;

public class RequestImageCaptcha implements HTMLRequest {

	private HttpClient httpClient;

	@Override
	public void submit(HTMLLocalContext htmlLocalContext)
			throws HTMLRequestException {

		String urlCaptcha = (String) htmlLocalContext
				.getParameter(PARAM_SEARCH_PORTABILITY_URL_CAPTCHA);
		if (urlCaptcha == null) {
			throw new HTMLRequestException("Throwble parameter "
					+ PARAM_SEARCH_PORTABILITY_URL_CAPTCHA + "is null");
		}
		try {
			if (urlCaptcha.charAt(0) == '/') {
				urlCaptcha = URL_HOST + urlCaptcha;
			}
		} catch (NullPointerException e) {
		} catch (IndexOutOfBoundsException e) {
		}
		HttpGet httpGet = new HttpGet(urlCaptcha);
		HttpResponse httpResponse;
		try {
			httpResponse = httpClient.execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK
					|| httpResponse.getEntity() == null) {
				throw new HTMLRequestException(
						"Status Code response invalid = "
								+ httpResponse.getStatusLine().getStatusCode());
			}
			try {
				byte[] bytesInputStream = EntityUtils.toByteArray(httpResponse
						.getEntity());
				ByteArrayInputStream inputStream = new ByteArrayInputStream(
						bytesInputStream);
				htmlLocalContext.setParameter(PARAM_IMAGE_CAPTCHA_STREAM,
						inputStream);
			} finally {
				httpResponse.getEntity().consumeContent();
			}
		} catch (ClientProtocolException e) {
			throw new HTMLRequestException("Throwable connection -"
					+ e.getMessage(), e);
		} catch (IOException e) {
			throw new HTMLRequestException("Throwable protocol HTTP -"
					+ e.getMessage(), e);

		}

	}

	public HttpClient getHttpClient() {
		return httpClient;
	}

	public void setHttpClient(HttpClient httpClient) {
		this.httpClient = httpClient;
	}

}
